﻿#include "CubeTexture.h"

#include <iostream>
#include <stb_img.h>

bool FCubeTexture::LoadFromFile(const std::array<FFileSys::path, 6>& FilePathArr, const bool FlipVertically)
{
	//uint8_t* ImgArray[6];

	//int32_t Index = 0;
	//for (const auto& Path : FilePathArr)
	//{
	//	int32_t Channels;
	//	//stbi_set_flip_vertically_on_load(FlipVertically);
	//	uint8_t* ImgData = stbi_load(Path.string().c_str(), &Width, &Height, &Channels, 0);
	//	if (!ImgData)
	//	{
	//		return false;
	//	}

	//	ImgArray[Index] = ImgData;
	//	Index++;
	//}

	//glGenTextures(1, &Handle);
	//glBindTexture(GL_TEXTURE_CUBE_MAP, Handle);

	//int32_t FaceIndex = 0;
	//for (auto& Img : ImgArray)
	//{
	//	glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + FaceIndex, 
	//		0, GL_RGB, Width, Height, 0, GL_RGB, GL_UNSIGNED_BYTE, Img
	//	);
	//	stbi_image_free(Img);
	//	FaceIndex++;
	//}

	//glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	//glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	//glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	//glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	//glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);

	unsigned int textureID;
	glGenTextures(1, &textureID);
	glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);

	stbi_set_flip_vertically_on_load(FlipVertically);

	int width, height, nrComponents;
	for (unsigned int i = 0; i < FilePathArr.size(); i++)
	{
		unsigned char *data = stbi_load(FilePathArr[i].string().c_str(), &width, &height, &nrComponents, 0);
		if (data)
		{
			glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
			stbi_image_free(data);
		}
		else
		{
			std::cout << "Cubemap texture failed to load at path: " << FilePathArr[i] << std::endl;
			stbi_image_free(data);
		}
	}
	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);

	Handle = textureID;

	return true;
}

void FCubeTexture::BindTextureUnit(const int32_t Index) const
{
	glActiveTexture(GL_TEXTURE0 + Index);
	glBindTexture(GL_TEXTURE_CUBE_MAP, Handle);
}
